package com.crysta1.picviewer;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
    private final List<ImageItem> imageItems;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivImage;
        TextView tvTitle, tvTime, tvUrl;

        public ViewHolder(View itemView) {
            super(itemView);
            ivImage = itemView.findViewById(R.id.iv_image);
            tvTitle = itemView.findViewById(R.id.tv_title);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvUrl = itemView.findViewById(R.id.tv_url);
        }
    }

    public ImageAdapter(List<ImageItem> imageItems) {
        this.imageItems = imageItems;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_image, parent, false);
        return new ViewHolder(view);
    }



    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ImageItem item = imageItems.get(position);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

        // 使用Glide加载图片
        Glide.with(holder.itemView)
                .load(item.url)
                .override(300, Target.SIZE_ORIGINAL)
                .placeholder(R.drawable.ic_placeholder)
                .fitCenter()
                .error(R.drawable.ic_error)
                .into(holder.ivImage);

        holder.tvTitle.setText(item.title);
        holder.tvTime.setText(sdf.format(item.addTime));
        holder.tvUrl.setText(item.url);

        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(v.getContext(), DetailActivity.class);
            intent.putExtra("position", position);
            v.getContext().startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return imageItems.size();
    }
}